package com.uniknow.app.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import com.uniknow.app.AppConfig;

import android.content.Context;


public class UploadUtil {
    public static String uploadFile(Context mContext,String filePath,String pageUrl,String uploadUrl){
    	String upload_status = "doing";
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "******";
        
        //图片限制大小
        try {
			filePath = changeImage(mContext,filePath);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        //TODO 对大图片进行剪裁
//        System.out.println("结束");
//        if(true){
//        	return "fail";
//        }
        try
        {
          URL url = new URL(uploadUrl);
          HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
          httpURLConnection.setDoInput(true);
          httpURLConnection.setDoOutput(true);
          httpURLConnection.setUseCaches(false);
          httpURLConnection.setRequestMethod("POST");
          httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
          httpURLConnection.setRequestProperty("Charset", "UTF-8");
          httpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);

          DataOutputStream dos = new DataOutputStream(httpURLConnection
              .getOutputStream());
          dos.writeBytes(twoHyphens + boundary + end);
          dos
              .writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
                  + filePath.substring(filePath.lastIndexOf("/") + 1)
                  + "\"" + end);
          dos.writeBytes(end);

		  if(!filePath.startsWith(FileUtils.SDPATH)){
				filePath = FileUtils.SDPATH + filePath;
		  }
		  System.out.println("UploadUtil filePath = "+filePath);
          FileInputStream fis = new FileInputStream(filePath);
          byte[] buffer = new byte[8192]; // 8k
          int count = 0;
          while ((count = fis.read(buffer)) != -1)
          {
            dos.write(buffer, 0, count);

          }
          fis.close();

          dos.writeBytes(end);
          dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
          dos.flush();

          InputStream is = httpURLConnection.getInputStream();
          InputStreamReader isr = new InputStreamReader(is, "utf-8");
          BufferedReader br = new BufferedReader(isr);
          String result = br.readLine();
          System.out.println("upload_result = "+result);
          //Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
          dos.close();
          is.close();
          upload_status = result.toString().trim();

        } catch (Exception e)
        {
          e.printStackTrace();
          upload_status = "fail";
          System.out.println("Upload 出错："+e.getMessage());
          UIHelper.ToastMessage(mContext, e.getMessage());
        }

//        try {
//            Thread.sleep(3000);//括号里面的5000代表5000毫秒，也就是5秒，可以该成你需要的时间
//	    } catch (InterruptedException e) {
//	            e.printStackTrace();
//	    }
        return upload_status;
    
    }
    
    public static String changeImage (Context mCOntex,String filePath) throws IOException{
    	if(!filePath.startsWith(FileUtils.SDPATH)){
			filePath = FileUtils.SDPATH + filePath;
    	}
    	String OraFilePath = filePath;
    	File Orafile = new File(filePath);
    	//TODO net.lianjiao.know.utils.ImageUtils.getBitmapByPath OOM 错误了
    	if(Orafile.length()>200000){
    		String fileName = FileUtils.getFileName(filePath);
	    	String changeFilePath = FileUtils.SDPATH+AppConfig.FOLDER_IMG+File.separator+"thumb"+fileName;
	    	System.out.println("fileName = "+fileName);
	    	if(fileName.endsWith(".png")||fileName.endsWith(".jpg")){
	    		ImageUtils.createImageThumbnail(mCOntex, filePath, changeFilePath, 768, 80,Orafile.length());
				File changeFile = new File(changeFilePath);
				if(changeFile.exists()){
					filePath = changeFilePath;
				}else{
					System.out.println("没找到图片，缩放失败");
				}
	    	}else{
	    		System.out.println("不是图片 fileName = "+fileName);
	    	}
    	}else{
    		System.out.println("不需要剪裁的图片 filePath = "+filePath);
    		System.out.println("文件＜200K Orafile.length()="+Orafile.length());
    	}
    	return filePath;
    }
}
